/**
 * @File SegmentValuesDaoImpl.java
 * @author Dheeraj Singh
 * @Version 1.0
 * @Date June 22, 2013
 * 
 * Copyright (c) 2011 EdRP, Dayalbagh Educational Institute.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this  list of conditions and the following disclaimer.
 *
 * Redistribution in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL ETRG OR ITS CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributors: Members of EdRP, Dayalbagh Educational Institute
 */

package in.ac.dei.edrp.generalLedger.segmentValues;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.ibatis.sqlmap.client.SqlMapClient;

@Component
@Qualifier("SegmentValuesDaoImpl")
public class SegmentValuesDaoImpl extends SqlMapClientDaoSupport implements SegmentValuesDao{

	private static Logger logObj = Logger.getLogger(SegmentValuesDaoImpl.class);
	
	SegmentValuesDaoImpl(){}
	
	@Autowired
	public SegmentValuesDaoImpl(SqlMapClient sqlMapClient){
		setSqlMapClient(sqlMapClient);
	}
	
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	public List<SegmentValuesBean> getSegmentDetails(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getSegments", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}

	public List<SegmentValuesBean> getSegmentValueDetails(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getSegmentValues", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}
	
	public List<SegmentValuesBean> getGroupDetails(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getGroups", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}


	public String saveEditSegments(List<Map<String, String>> saveRecord, SegmentValuesBean input) {
		String str = "";
		try{
			if(saveRecord.size() > 0){
				for(int i = 0; i < saveRecord.size(); i++){
					input.setSegmentValue(saveRecord.get(i).get("segmentValue"));
					input.setSegmentDescription(saveRecord.get(i).get("segmentDescription"));
					if(saveRecord.get(i).get("segmentLevel") == "")
						input.setSegmentLevel("0");
					else
						input.setSegmentLevel(saveRecord.get(i).get("segmentLevel"));
					
					if(saveRecord.get(i).get("isParent").equalsIgnoreCase("Yes")){
						if(saveRecord.get(i).get("segmentGroup") != ""){
							String[] group = saveRecord.get(i).get("segmentGroup").split("-");
							input.setSegmentGroup(group[0]);
						}else{
							input.setSegmentGroup("");
						}
					}else{
						input.setSegmentGroup("");
					}
					input.setIsParent(saveRecord.get(i).get("isParent"));
					getSqlMapClientTemplate().update("segmentValues.updateSegments", input);
				}
			}
			str = "saved";
		}catch(Exception ex){
			logObj.error(ex);
		}
		return str;
	}
	
	@SuppressWarnings("unchecked")
	public String saveNewSegments(final List<Map<String, String>> saveRecord, final SegmentValuesBean input) {
		String message = "failure";
		message=(String)transactionTemplate.execute(new TransactionCallback(){
		Object savepoint = null;
		String result="failure";
		
		public String doInTransaction(TransactionStatus status) {
			savepoint = status.createSavepoint();
			int i = 0;
				try{
					if(saveRecord.size() > 0){
						for(i = 0; i < saveRecord.size(); i++){
							input.setSegmentValue(saveRecord.get(i).get("segmentValue"));
							input.setSegmentDescription(saveRecord.get(i).get("segmentDescription"));
							if(saveRecord.get(i).get("segmentGroup") != ""){
								String[] group = saveRecord.get(i).get("segmentGroup").split("-");
								input.setSegmentGroup(group[0]);
							}else{
								input.setSegmentGroup("");
							}
							input.setIsParent(saveRecord.get(i).get("isParent"));
							if(saveRecord.get(i).get("segmentLevel") == "")
								input.setSegmentLevel("0");
							else
								input.setSegmentLevel(saveRecord.get(i).get("segmentLevel"));
				
							getSqlMapClientTemplate().insert("segmentValues.insertSegments", input);
						}
					}
					result = i + "success";
				}catch(Exception ex){
					ex.printStackTrace();
					logObj.error(ex);
					result = i + ex.getClass().toString();
					status.rollbackToSavepoint(savepoint);
				}
				return result;
			}
		});
		return message;
	}

	public String deleteSegments(SegmentValuesBean input) {
		String str = "";
		try{
			getSqlMapClientTemplate().delete("segmentValues.deleteSegmentValues", input);
			str = "deleted";
		}catch(Exception ex){
			logObj.error(ex);
		}
		return str;
	}

	public List<SegmentValuesBean> getAccountTypes(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getAccountTypes", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}


	public List<SegmentValuesBean> getChildDetails(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getChildRange", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public String saveChildRanges(final List<Map<String, String>> saveRecord,
			final SegmentValuesBean input) {
		String message = "failure";
		message=(String)transactionTemplate.execute(new TransactionCallback(){
		Object savepoint = null;
		String result="failure";
		
		public String doInTransaction(TransactionStatus status) {
			savepoint = status.createSavepoint();
			int i = 0;
				try{
					if(saveRecord.size() > 0){
						for(i = 0; i < saveRecord.size(); i++){
							
							if(saveRecord.get(i).get("includeFlag").equalsIgnoreCase("Child Values Only")){
								input.setIncludeFlag("C");
							}else if(saveRecord.get(i).get("includeFlag").equalsIgnoreCase("Parent Values Only")){
								input.setIncludeFlag("P");
							}else{
								input.setIncludeFlag(saveRecord.get(i).get("includeFlag"));
							}
							
							input.setChildRangeFrom(saveRecord.get(i).get("childRangeFrom"));
							input.setChildRangeTo(saveRecord.get(i).get("childRangeTo"));

							if(saveRecord.get(i).get("oldChildRangeFrom").equalsIgnoreCase("") && saveRecord.get(i).get("oldChildRangeTo").equalsIgnoreCase("")){
								getSqlMapClientTemplate().insert("segmentValues.setChildRange", input);
							}else{
								input.setOldChildRangeFrom(saveRecord.get(i).get("oldChildRangeFrom"));
								input.setOldChildRangeTo(saveRecord.get(i).get("oldChildRangeTo"));
								getSqlMapClientTemplate().update("segmentValues.updateChildRange", input);
							}
						}
					}
					result = i + "success";
				}catch(Exception ex){
					ex.printStackTrace();
					logObj.error(ex);
					result = i + ex.getClass().toString();
					status.rollbackToSavepoint(savepoint);
				}
				return result;
			}
		});
		return message;
	}

	public List<SegmentValuesBean> getAllApplications(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getAllApplications", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}

	public List<SegmentValuesBean> getAllFlexFields(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getAllFlexFieldIds", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}

	public List<SegmentValuesBean> getAllKeyFlexFields(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getAllKeyFlexFieldIds", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}

	public List<SegmentValuesBean> viewHierarchy(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> returnList = new ArrayList<SegmentValuesBean>();
		try{
			List<SegmentValuesBean> rangeList = new ArrayList<SegmentValuesBean>();
			rangeList = getSqlMapClient().queryForList("segmentValues.getChildRangesForParent", segmentValuesBean);
			if(rangeList.size() > 0){
				for(int i = 0; i < rangeList.size(); i++){
					segmentValuesBean.setChildRangeFrom(rangeList.get(i).getChildRangeFrom());
					segmentValuesBean.setChildRangeTo(rangeList.get(i).getChildRangeTo());
					List<SegmentValuesBean> valueList = new ArrayList<SegmentValuesBean>();
					valueList = getSqlMapClient().queryForList("segmentValues.getValuesInRange", segmentValuesBean);
					for(int j = 0; j < valueList.size(); j++){
						SegmentValuesBean input = new SegmentValuesBean();
						input.setSegmentValue(valueList.get(j).getSegmentValue());
						input.setSegmentDescription(valueList.get(j).getSegmentDescription());
						input.setIsParent(valueList.get(j).getIsParent());
						returnList.add(input);
					}
				}
			}
		}catch(Exception ex){
			logObj.error(ex);
		}
		return returnList;
	}

	public List<SegmentValuesBean> showDownHierarchy(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> returnList = new ArrayList<SegmentValuesBean>();
		try{
			List<SegmentValuesBean> rangeList = new ArrayList<SegmentValuesBean>();
			rangeList = getSqlMapClient().queryForList("segmentValues.getChildRangesForParent", segmentValuesBean);
			if(rangeList.size() > 0){
				for(int i = 0; i < rangeList.size(); i++){
					segmentValuesBean.setChildRangeFrom(rangeList.get(i).getChildRangeFrom());
					segmentValuesBean.setChildRangeTo(rangeList.get(i).getChildRangeTo());
					List<SegmentValuesBean> valueList = new ArrayList<SegmentValuesBean>();
					valueList = getSqlMapClient().queryForList("segmentValues.getValuesInRange", segmentValuesBean);
					for(int j = 0; j < valueList.size(); j++){
						SegmentValuesBean input = new SegmentValuesBean();
						input.setSegmentValue(valueList.get(j).getSegmentValue());
						input.setSegmentDescription(valueList.get(j).getSegmentDescription());
						input.setIsParent(valueList.get(j).getIsParent());
						returnList.add(input);
					}
				}
			}
		}catch(Exception ex){
			logObj.error(ex);
		}
		return returnList;
	}

	public List<SegmentValuesBean> getParentForUpwards(
			SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getParentForUpwards", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}

	public List<SegmentValuesBean> getValues(SegmentValuesBean segmentValuesBean) {
		List<SegmentValuesBean> list = null;
		try{
			list = getSqlMapClientTemplate().queryForList("segmentValues.getValues", segmentValuesBean);
		}catch(Exception ex){
			logObj.error(ex);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public String moveChildRange(final List<Map<String, String>> moveRecord,
			final SegmentValuesBean input) {
		String message = "failure";
		message=(String)transactionTemplate.execute(new TransactionCallback(){
		Object savepoint = null;
		String result="failure";
		
		public String doInTransaction(TransactionStatus status) {
			savepoint = status.createSavepoint();
				try{
					if(moveRecord.size() > 0){
						for(int i = 0; i < moveRecord.size(); i++){
							input.setChildRangeFrom(moveRecord.get(i).get("childRangeFrom"));
							input.setChildRangeTo(moveRecord.get(i).get("childRangeTo"));
							if(moveRecord.get(i).get("includeFlag").equalsIgnoreCase("Child Values Only")){
								input.setIncludeFlag("C");
							}else if(moveRecord.get(i).get("includeFlag").equalsIgnoreCase("Parent Values Only")){
								input.setIncludeFlag("P");
							}else{
								input.setIncludeFlag(moveRecord.get(i).get("includeFlag"));
							}
							getSqlMapClient().update("segmentValues.moveChildRange", input);
						}
					}
					
					result = "success";
				}catch(Exception ex){
					ex.printStackTrace();
					logObj.error(ex);
					result = ex.getClass().toString();
					status.rollbackToSavepoint(savepoint);
				}
				return result;
			}
		});
		return message;
	}
}
